import { ref } from 'vue';
import { defineStore } from 'pinia';
import { SiteConfig } from './config';
import { fetchCategoryByWebsiteCode, fetchWebsiteList } from '@/api/website';
import { Category } from '@/types/category';

export const useCategoryStore = defineStore('categoryStore', () => {
  const selectedCategory = ref(st.get('_category') ?? {});

  function setSelectCategory(obj: any) {
    selectedCategory.value = obj;
    st.set('_category', obj);
  }

  // 所有类目集合
  // const categoryList = ref<WebSite[]>([]);
  const webSites = ref<SiteConfig[]>([]);
  const categoryMap = ref<Map<string, Category[]>>(new Map());

  const getWebsites = async () => {
    if (!webSites.value.length) {
      const res = await fetchWebsiteList();
      useRes(res, () => {
        webSites.value = res.data;
      });
    }
    return webSites.value;
  };
  const getCategoryList = async (websiteCode: string) => {
    if (!categoryMap.value.has(websiteCode)) {
      const res = await fetchCategoryByWebsiteCode({
        websiteCode,
        hasSplits: true,
        removeOrigin: true,
      });
      useRes(res, () => {
        categoryMap.value.set(websiteCode, res.data.categoryList);
      });
    }
    return categoryMap.value.get(websiteCode) || [];
  };
  return { setSelectCategory, selectedCategory, getWebsites, getCategoryList };
});
